package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.enums.HouseholdBdEnum;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.enums.SchoolDictEnum;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdKeyVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdQueryVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduHouseholdBd.EduHouseholdBdQueryVO;
import com.jwsoft.manager.common.vo.eduHouseholdBd.EduHouseholdBdVO;
import com.jwsoft.manager.common.vo.eduStudentStatus.EduStudentStatusVO;
import com.jwsoft.manager.common.vo.individuation.HouseHoldSaveVO;
import com.jwsoft.manager.core.dao.model.EduHousehold;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollPre;
import com.jwsoft.manager.core.dao.model.EduhHousehold;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduHouseholdIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.integration.common.DygxIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 户籍信息表业务实现类
 *
 * @author wangtao
 * @since 2022-12-02
 */
@ApiService(funcCode = "eduHousehold", title = "户籍信息表")
public class EduHouseholdIntegrationImpl implements EduHouseholdIntegration {

    @Autowired
    public EduHouseholdService eduHouseholdService;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;

    @Autowired
    public DygxIntegration dygxIntegration;

    @Resource
    public OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    public EduAddressService eduAddressService;
    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private CommonIntegration commonIntegration;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private RedisHelper redisHelper;
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    public static final String APP_HOUSEHOLD_LIMIT = "APP_HOUSEHOLD_LIMIT_";
    public static final String get_household = "APP_HOUSEHOLD_IDCARD_";
    @Autowired
    public DictHelper dictHelper;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;

    @Autowired
    private EduHouseholdBdIntegrationImpl eduHouseholdBdIntegration;
    @Autowired
    private EduStudentHouseService eduStudentHouseService;

    @Autowired
    private EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhHouseholdService eduhHouseholdService;
    public static final String handleTable = "edu_household";

    @Override
    @OpApi(funcCode = "eduHousehold0001", title = "户籍信息表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduHouseholdVO> getList(EduHouseholdQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null){
            desensitizeFlag = true;
        }
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        if (!queryHistoryFlag) {
            QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
            householdQueryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getIdcard()), EduHousehold::getIdcard, vo.getIdcard())
                    .eq(StringUtils.isNotBlank(vo.getFullName()), EduHousehold::getFullName, vo.getFullName())
                    .eq(StringUtils.isNotBlank(vo.getHh()), EduHousehold::getHh, vo.getHh())
                    .eq(StringUtils.isNotBlank(vo.getSex()), EduHousehold::getSex, vo.getSex())
                    .eq(StringUtils.isNotBlank(vo.getCountry()), EduHousehold::getCountry, vo.getCountry())
                    .eq(StringUtils.isNotBlank(vo.getNation()), EduHousehold::getNation, vo.getNation())
                    .eq(StringUtils.isNotBlank(vo.getStreet()), EduHousehold::getStreet, vo.getStreet())
                    .eq(StringUtils.isNotBlank(vo.getMaritalStatus()), EduHousehold::getMaritalStatus, vo.getMaritalStatus())
                    .eq(StringUtils.isNotBlank(vo.getCulturalLevel()), EduHousehold::getCulturalLevel, vo.getCulturalLevel())
                    .eq(StringUtils.isNotBlank(vo.getBloodType()), EduHousehold::getBloodType, vo.getBloodType())
                    .like(StringUtils.isNotBlank(vo.getAddress()), EduHousehold::getAddress, Convert.toDBC(vo.getAddress()))
                    .ge(StringUtils.isNotBlank(vo.getYxqxqsrq()), EduHousehold::getYxqxqsrq, vo.getYxqxqsrq())
                    .le(StringUtils.isNotBlank(vo.getYxqxjzrq()), EduHousehold::getYxqxjzrq, vo.getYxqxjzrq())

                    .eq(ObjectUtils.isNotEmpty(vo.getYear()), EduHousehold::getYear, vo.getYear())
                    .eq(StringUtils.isNotBlank(vo.getAreaCode()), EduHousehold::getAreaCode, vo.getAreaCode())
                    .eq(StringUtils.isNotBlank(vo.getAuthStatus()), EduHousehold::getAuthStatus, vo.getAuthStatus())
                    .eq(StringUtils.isNotBlank(vo.getStatus()), EduHousehold::getStatus, vo.getStatus());
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduHousehold> list = eduHouseholdService.list(householdQueryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduHousehold> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduHouseholdVO> resultList = Convert.toList(EduHouseholdVO.class, pageInfo.getList());
            if (desensitizeFlag) {
                for (EduHouseholdVO eduStudentHouseVO : resultList) {
                    eduStudentHouseVO.setIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentHouseVO.getIdcard()));
                    eduStudentHouseVO.setFullName(EduDesensitizeUtil.desensitizeFullName(eduStudentHouseVO.getFullName()));
                    eduStudentHouseVO.setHouseholder(EduDesensitizeUtil.desensitizeFullName(eduStudentHouseVO.getHouseholder()));
                    eduStudentHouseVO.setHouseholderIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentHouseVO.getHouseholderIdcard()));
                    eduStudentHouseVO.setAddress(EduDesensitizeUtil.desensitizeAddress(eduStudentHouseVO.getAddress()));

                }
            }
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }else {
            // 迁移过后，判断是否加密
            Boolean encryptFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), handleTable));
            //如果加密，把查询条件加密
            if (encryptFlag) {
                if (StringUtils.isNotBlank(vo.getIdcard())){
                    vo.setIdcard(CommonSecureUtil.sm4Encrypt(vo.getIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getFullName())){
                    vo.setFullName(CommonSecureUtil.sm4Encrypt(vo.getFullName()));
                }
                if (StringUtils.isNotBlank(vo.getBeforeName())){
                    vo.setBeforeName(CommonSecureUtil.sm4Encrypt(vo.getBeforeName()));
                }
                if (StringUtils.isNotBlank(vo.getAddress())){
                    vo.setAddress(CommonSecureUtil.sm4Encrypt(vo.getAddress()));
                }
                if (StringUtils.isNotBlank(vo.getHouseholdPlace())){
                    vo.setHouseholdPlace(CommonSecureUtil.sm4Encrypt(vo.getHouseholdPlace()));
                }
                if (StringUtils.isNotBlank(vo.getHouseholder())){
                    vo.setHouseholder(CommonSecureUtil.sm4Encrypt(vo.getHouseholder()));
                }
                if (StringUtils.isNotBlank(vo.getHouseholderIdcard())){
                    vo.setHouseholderIdcard(CommonSecureUtil.sm4Encrypt(vo.getHouseholderIdcard()));
                }
            }
            QueryWrapper<EduhHousehold> householdQueryWrapper = new QueryWrapper<>();
            householdQueryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getIdcard()), EduhHousehold::getIdcard, vo.getIdcard())
                    .eq(StringUtils.isNotBlank(vo.getFullName()), EduhHousehold::getFullName, vo.getFullName())
                    .eq(StringUtils.isNotBlank(vo.getHh()), EduhHousehold::getHh, vo.getHh())
                    .eq(StringUtils.isNotBlank(vo.getSex()), EduhHousehold::getSex, vo.getSex())
                    .eq(StringUtils.isNotBlank(vo.getCountry()), EduhHousehold::getCountry, vo.getCountry())
                    .eq(StringUtils.isNotBlank(vo.getNation()), EduhHousehold::getNation, vo.getNation())
                    .eq(StringUtils.isNotBlank(vo.getStreet()), EduhHousehold::getStreet, vo.getStreet())
                    .eq(StringUtils.isNotBlank(vo.getMaritalStatus()), EduhHousehold::getMaritalStatus, vo.getMaritalStatus())
                    .eq(StringUtils.isNotBlank(vo.getCulturalLevel()), EduhHousehold::getCulturalLevel, vo.getCulturalLevel())
                    .eq(StringUtils.isNotBlank(vo.getBloodType()), EduhHousehold::getBloodType, vo.getBloodType())
                    .like(StringUtils.isNotBlank(vo.getAddress()), EduhHousehold::getAddress, Convert.toDBC(vo.getAddress()))
                    .ge(StringUtils.isNotBlank(vo.getYxqxqsrq()), EduhHousehold::getYxqxqsrq, vo.getYxqxqsrq())
                    .le(StringUtils.isNotBlank(vo.getYxqxjzrq()), EduhHousehold::getYxqxjzrq, vo.getYxqxjzrq())

                    .eq(ObjectUtils.isNotEmpty(vo.getYear()), EduhHousehold::getYear, vo.getYear())
                    .eq(StringUtils.isNotBlank(vo.getAreaCode()), EduhHousehold::getAreaCode, vo.getAreaCode())
                    .eq(StringUtils.isNotBlank(vo.getAuthStatus()), EduhHousehold::getAuthStatus, vo.getAuthStatus())
                    .eq(StringUtils.isNotBlank(vo.getStatus()), EduhHousehold::getStatus, vo.getStatus());
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduhHousehold> list = eduhHouseholdService.list(householdQueryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduhHousehold> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduHouseholdVO> resultList = Convert.toList(EduHouseholdVO.class, pageInfo.getList());
            for (EduHouseholdVO eduHouseholdVO : resultList) {
                if ("1".equals(eduHouseholdVO.getEncryptFlag())) {
                    if (StringUtils.isNotBlank(eduHouseholdVO.getIdcard())){
                        eduHouseholdVO.setIdcard(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getIdcard()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getFullName())){
                        eduHouseholdVO.setFullName(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getFullName()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getBeforeName())){
                        eduHouseholdVO.setBeforeName(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getBeforeName()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getAddress())){
                        eduHouseholdVO.setAddress(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getAddress()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getHouseholdPlace())){
                        eduHouseholdVO.setHouseholdPlace(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getHouseholdPlace()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getHouseholder())){
                        eduHouseholdVO.setHouseholder(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getHouseholder()));
                    }
                    if (StringUtils.isNotBlank(eduHouseholdVO.getHouseholderIdcard())){
                        eduHouseholdVO.setHouseholderIdcard(CommonSecureUtil.sm4Decrypt(eduHouseholdVO.getHouseholderIdcard()));
                    }
                }
            }
            if (desensitizeFlag) {
                for (EduHouseholdVO eduStudentHouseVO : resultList) {
                    eduStudentHouseVO.setIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentHouseVO.getIdcard()));
                    eduStudentHouseVO.setFullName(EduDesensitizeUtil.desensitizeFullName(eduStudentHouseVO.getFullName()));
                    eduStudentHouseVO.setHouseholder(EduDesensitizeUtil.desensitizeFullName(eduStudentHouseVO.getHouseholder()));
                    eduStudentHouseVO.setHouseholderIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentHouseVO.getHouseholderIdcard()));
                    eduStudentHouseVO.setAddress(EduDesensitizeUtil.desensitizeAddress(eduStudentHouseVO.getAddress()));

                }
            }
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }


    @Override
    @OpApi(funcCode = "eduHousehold0002", title = "户籍信息表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduHouseholdVO getById(EduHouseholdKeyVO vo) {
        //判断是否迁移过
        EduHouseholdVO result;
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), handleTable));
        if (!queryHistoryFlag) {
            EduHousehold entity = eduHouseholdService.getById(vo.getHouseholdId());
            if (ObjectUtils.isEmpty(entity)) {
                throw new AppException("查询不到详细信息!");
            }
            result = Convert.convert(EduHouseholdVO.class, entity);
        }else {
            EduhHousehold eduhHousehold = eduhHouseholdService.getById(vo.getHouseholdId());
            if (ObjectUtils.isEmpty(eduhHousehold)){
                throw new AppException("查询不到详细信息!");
            }
            if ("1".equals(eduhHousehold.getEncryptFlag())) {
                if (StringUtils.isNotBlank(eduhHousehold.getIdcard())){
                    eduhHousehold.setIdcard(CommonSecureUtil.sm4Decrypt(eduhHousehold.getIdcard()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getFullName())){
                    eduhHousehold.setFullName(CommonSecureUtil.sm4Decrypt(eduhHousehold.getFullName()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getBeforeName())){
                    eduhHousehold.setBeforeName(CommonSecureUtil.sm4Decrypt(eduhHousehold.getBeforeName()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getAddress())){
                    eduhHousehold.setAddress(CommonSecureUtil.sm4Decrypt(eduhHousehold.getAddress()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getHouseholdPlace())){
                    eduhHousehold.setHouseholdPlace(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholdPlace()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getHouseholder())){
                    eduhHousehold.setHouseholder(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholder()));
                }
                if (StringUtils.isNotBlank(eduhHousehold.getHouseholderIdcard())){
                    eduhHousehold.setHouseholderIdcard(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholderIdcard()));
                }
            }
            result = Convert.convert(EduHouseholdVO.class, eduhHousehold);
        }
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduHousehold0003", title = "户籍信息表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduHouseholdVO vo) {
        if (StringUtils.isBlank(vo.getYear())){
            throw new AppException("所属招生年度不能为空");
        }
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduHousehold0004", title = "户籍信息表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduHousehold0004",
            operationName = "户籍信息表新增",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseholdVO add(EduHouseholdVO vo) {
        //保存前校验
        checkSave(vo);
        Integer year=eduHelper.thisYear();
        if (year-Integer.parseInt(vo.getYear())!=0) {
            throw new AppException("只能新增招生当前年度的数据!");
        }
        //保存数据
        EduHousehold entity = Convert.convert(EduHousehold.class, vo);

        QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
        householdQueryWrapper.lambda()
                .eq(!org.springframework.util.ObjectUtils.isEmpty(vo.getIdcard()), EduHousehold::getIdcard, vo.getIdcard())
                .eq(!org.springframework.util.ObjectUtils.isEmpty(vo.getStatus()), EduHousehold::getStatus, "1")
                .eq(!org.springframework.util.ObjectUtils.isEmpty(vo.getStatus()), EduHousehold::getAuthStatus, "1")
                .eq(!org.springframework.util.ObjectUtils.isEmpty(vo.getYear()), EduHousehold::getYear, vo.getYear());
        if (eduHouseholdService.count(householdQueryWrapper) > 0) {
            throw new AppException("同一个身份证，同一年度不能维护多条数据!");
        }


        Boolean enrollFlag = this.checkEnroll(vo.getIdcard(), eduHelper.thisYear());
        if (enrollFlag) {
            throw new AppException("已存在报名数据，不能登记!");
        }
        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, vo.getIdcard())
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, vo.getIdcard())
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, vo.getIdcard());
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        String bnxxFlag="0";
        String bnczFlag="0";
        if (!CollectionUtils.isEmpty(list)){
            for(EduStudentEnrollPre pre:list){
                if(SchoolCategoryEnum.PRIMARY.getType().equals(pre.getSchoolCategory())){
                    bnxxFlag="1";
                }
                if(SchoolCategoryEnum.JUNIOR.getType().equals(pre.getSchoolCategory())){
                    bnczFlag="1";
                }
            }
        }
        String addressId =
                eduAddressService.saveByAddress(vo.getAddress(),Integer.parseInt(vo.getYear()),bnxxFlag,bnczFlag);
        entity.setAddressId(addressId);
        eduHouseholdService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setHouseholdId(entity.getHouseholdId());
        clearCache(entity.getIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduHousehold0005", title = "户籍信息表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduHousehold0005",
            operationName = "户籍信息表修改",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseholdVO edit(EduHouseholdVO vo) {
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(Integer.valueOf(vo.getYear()), handleTable));
        if (queryHistoryFlag) {
            throw new AppException("历史数据无法修改");
        }
        if (ObjectUtils.isEmpty(vo.getHouseholdId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        Integer year=eduHelper.thisYear();
        if (year-Integer.parseInt(vo.getYear())!=0) {
            throw new AppException("只能修改招生当前年度的数据!");
        }
        EduHousehold oldEntity = eduHouseholdService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, vo.getIdcard())
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, vo.getIdcard())
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, vo.getIdcard());
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        String bnxxFlag="0";
        String bnczFlag="0";
        if (!CollectionUtils.isEmpty(list)){
            for(EduStudentEnrollPre pre:list){
                if(SchoolCategoryEnum.PRIMARY.getType().equals(pre.getSchoolCategory())){
                    bnxxFlag="1";
                }
                if(SchoolCategoryEnum.JUNIOR.getType().equals(pre.getSchoolCategory())){
                    bnczFlag="1";
                }
            }
        }
        String addressId =
                eduAddressService.saveByAddress(vo.getAddress(),Integer.parseInt(vo.getYear()),bnxxFlag,bnczFlag);
        vo.setAddressId(addressId);

        //保存数据
        EduHousehold entity = Convert.convert(EduHousehold.class, vo);
        eduHouseholdService.updateById(entity);
        clearCache(entity.getIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduHousehold0006", title = "户籍信息表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduHousehold0006",
            operationName = "户籍信息表删除",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduHouseholdKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseholdId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduHousehold entity = eduHouseholdService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduHouseholdService.removeById(vo.getHouseholdId());
        clearCache(entity.getIdcard());
    }

    //清除缓存
    private void clearCache(String idcard) {
        //查询人员
        if (StringUtils.isBlank(idcard)) {
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper = new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId, EduStudentEnrollPre::getIdcard, EduStudentEnrollPre::getFatherIdcard, EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear, eduHelper.thisYear())
                .and(wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (EduStudentEnrollPre pre : list) {
            //户籍
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }

    @Override
    @OpApi(
            funcCode = "eduHousehold0007",
            title = "户籍接口信息获取并保存",
            funcType = FuncTypeEnum.other)
    public EduHouseholdVO saveHouseHoldData(HouseHoldSaveVO vo) {
        String idcard = vo.getIdcard();
        if (StringUtils.isBlank(idcard)) {
            throw new AppException("请传入需要同步户籍的身份证信息");
        }
        if (StringUtils.isBlank(vo.getStudentEnrollPreId())) {
            throw new AppException("请传入需要同步户籍的学生预采集id");
        }
        //判断当前年度是否已报名
        Boolean flag = this.checkEnroll(idcard, null);
        if (flag) {
            throw new AppException("已报名，不能同步户籍数据");
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        if (vo.getLocalFlag() == null) {
            vo.setLocalFlag(false);
        }
        ApiModel apiModel = eduHelper.getEduFunc("saveHouseHoldData", vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduHouseholdVO> list = (List<EduHouseholdVO>) apiModel.getMethod().invoke(bean, vo);
                if (StringUtils.isNotBlank(vo.getStudentEnrollPreId())) {
                    boolean syncFlag = false;
                    if (!vo.getLocalFlag()) {
                        CommonVO commonIrsAsyncVO = new CommonVO();
                        commonIrsAsyncVO.setParamKey("irs_async");
                        commonIrsAsyncVO.setAreaCode(vo.getAreaCode());
                        String irsAsync = commonIntegration.getValueByKeyAndArea(commonIrsAsyncVO);
                        if (BoolEnum.TRUE.getType().equalsIgnoreCase(irsAsync) || "true".equalsIgnoreCase(irsAsync)) {
                            syncFlag = true;
                        }
                    }

                    //同步数据后把比对标识改为未比对
                    UpdateWrapper<EduStudentEnrollPre> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.lambda().eq(EduStudentEnrollPre::getStudentEnrollPreId, vo.getStudentEnrollPreId())
                            .set(EduStudentEnrollPre::getHouseholdSyncFlag, syncFlag ? "3" : BoolEnum.TRUE.getType())//3同步中
                            .set(EduStudentEnrollPre::getBeforeFlag, BoolEnum.FALSE.getType());
                    EduStudentEnrollPre pre=eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
                    if(pre!=null&&!"2".equalsIgnoreCase(pre.getConsistentType())){
                        //人工处理过的数据，不重新比对
                        updateWrapper.lambda().set(EduStudentEnrollPre::getConsistentFlag,BoolEnum.FALSE.getType())
                                .set(EduStudentEnrollPre::getHouseholdId,null);
                    }
                    eduStudentEnrollPreService.update(updateWrapper);
                }
                if (!CollectionUtils.isEmpty(list)) {
                    EduHouseholdVO retVO = null;
                    for (EduHouseholdVO eduHouseholdVO : list) {
                        if (vo.getIdcard().equalsIgnoreCase(eduHouseholdVO.getIdcard())) {
                            retVO = eduHouseholdVO;
                            break;
                        }
                    }
                    return retVO;
                }
            } else {
                throw new AppException("未查询到方法");
            }
        } catch (AppException e) {
            throw e;
        } catch (InvocationTargetException e) {
            try {
                AppException exception = (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(), e.getTargetException());
            } catch (Exception ex) {
                throw new AppException(e.getCause().getMessage(), e.getTargetException());
            }

        } catch (Exception e) {
            throw new AppException(e.getMessage(), e);
        }
        return null;
    }

    @Override
    @OpApi(
            funcCode = "eduHousehold0008",
            title = "户籍接口信息获取并保存",
            funcType = FuncTypeEnum.other,
            checkPrivilege = BoolEnum.FALSE,
            savelog = true)
    public EduHouseholdVO queryHouseHoldDataApp(HouseHoldSaveVO vo) {
        if(StringUtils.isBlank(vo.getStudentEnrollPreId())){
            throw new AppException("预采集id不能为空");
        }
        //同一身份证一天最多同步获取5次
        String key = get_household + vo.getIdcard();
        Integer getCount = (Integer) redisHelper.get(key);
        if (getCount == null || getCount == 0) {
            getCount = 1;
        } else {
            getCount = getCount + 1;
        }
        redisHelper.set(key, getCount, 43200);
        if (getCount > 3) {
            throw new AppException("24小时内最多获取三次，如还有问题，请致电联系");
        }
        Object maxObj = redisHelper.get(APP_HOUSEHOLD_LIMIT + DateUtil.today());
        int max;
        if (org.springframework.util.ObjectUtils.isEmpty(maxObj)) {
            redisHelper.set(APP_HOUSEHOLD_LIMIT + DateUtil.today(), 1);
            max = 1;
        } else {
            max = (int) redisHelper.get(APP_HOUSEHOLD_LIMIT + DateUtil.today());
            max++;
            redisHelper.set(APP_HOUSEHOLD_LIMIT + DateUtil.today(), max);
        }
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("APP_HOUSEHOLD_LIMIT");
        String limit = commonIntegration.getValueByKey(commonVO);
        EduHouseholdVO eduHouseholdVO = null;
        if (!org.springframework.util.ObjectUtils.isEmpty(limit) && max > Integer.parseInt(limit)) {
            throw new AppException("今日大数据接口已达上限，请明日再试！");
        } else {
            Boolean enrollFlag= this.checkEnroll(vo.getIdcard(),eduHelper.thisYear());
            if(enrollFlag){
                throw new AppException("已存在报名数据，不能重新获取数据!");
            }
            eduHouseholdVO = saveHouseHoldData(vo);
        }
        if (StringUtils.isNotBlank(vo.getStudentEnrollPreId())) {
            EduStudentEnrollPre pre = eduStudentEnrollPreService.getById(vo.getStudentEnrollPreId());
            if (pre != null) {
                if (StringUtils.isNotBlank(pre.getIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());

                }
                if (StringUtils.isNotBlank(pre.getFatherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());

                }
                if (StringUtils.isNotBlank(pre.getMotherIdcard())) {
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());

                }
                eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
            }
        }
        return eduHouseholdVO;
    }

    @Override
    @OpApi(funcCode = "eduHousehold0009", title = "大数据户籍信息表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduHouseholdVO> queryBigDataHousehold(HouseHoldSaveVO vo) {
        String idcard = vo.getIdcard();
        String areaCode = vo.getAreaCode();
        if (StringUtils.isBlank(idcard)) {
            throw new AppException("请输入需要查询户籍的身份证信息");
        }
        if (!IdcardUtil.isValidCard(idcard)) {
            throw new AppException("证件号码有误!");
        }
        //如果查询条件未选择统筹区，则将当前登陆用户的统筹区作为条件查询
        if (StringUtils.isBlank(areaCode)) {
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        // 开启分页
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        ApiModel apiModel = eduHelper.getEduFunc("queryBigDataHousehold", vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduHouseholdVO> list = (List<EduHouseholdVO>) apiModel.getMethod().invoke(bean, vo);
                if (CollectionUtils.isEmpty(list)) {
                    // 判断是否为空，为空则返回空参数
                    return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
                }
                // 不为空则获取分页结果
                PageInfo<EduHouseholdVO> pageInfo = new PageInfo<>(list);

                return pageInfo;
            } else {
                throw new AppException("未查询到方法");
            }
        } catch (AppException e) {
            throw e;
        } catch (InvocationTargetException e) {
            try {
                AppException exception = (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(), e.getTargetException());
            } catch (Exception ex) {
                throw new AppException(e.getCause().getMessage(), e.getTargetException());
            }

        } catch (Exception e) {
            throw new AppException(e.getMessage(), e);
        }
    }

    @Override
    @OpApi(funcCode = "eduHousehold0010", title = "比对学生报名户籍信息", funcType = FuncTypeEnum.update)
    public void bdStudentHouseld(EduHouseholdQueryVO vo) {
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        //查询出学生报名信息
        EduHouseholdBdQueryVO queryVO = new EduHouseholdBdQueryVO();
        queryVO.setYear(eduHelper.thisYear());
        boolean isLastPage = false;
        while (!isLastPage){
            isLastPage = checkToExecute();
        }
    }

    private Boolean checkToExecute() {
        EduHouseholdBdQueryVO queryVO = new EduHouseholdBdQueryVO();
        queryVO.setYear(eduHelper.thisYear());
        queryVO.setBdStatus(HouseholdBdEnum.wbd.getType());
        PageInfo<EduHouseholdBdVO> studentEnrolls = eduHouseholdBdIntegration.getList(queryVO);
        List<EduHouseholdBdVO> list = studentEnrolls.getList();
        if (!ObjectUtils.isEmpty(list)) {
            //取list中的数据进行判断,处理数据
            checkStudentHousehold(list);
        }
        boolean isLastPage = studentEnrolls.isIsLastPage();
        return isLastPage;
    }

    //获取学生报名数据，比对户籍信息，
    private void checkStudentHousehold(List<EduHouseholdBdVO> list) {
        //1，遍历学生数据
        if (ObjectUtils.isEmpty(list)) {
            return;
        }
        List<EduHouseholdBdVO> updatedItems = new ArrayList<>();
        for (EduHouseholdBdVO item : list) {
            //2，查询户籍表有无学生信息，有设置进去，没有调用大数据接口查询
            QueryWrapper<EduHousehold> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(EduHousehold::getYear, item.getYear())
                    .eq(EduHousehold::getIdcard, item.getIdcard());
            EduHousehold household = eduHouseholdService.getOne(queryWrapper, false);
            if (household != null) {
                if (household.getHouseholdPlace() != null) {
                    item.setHouseholdPlace(household.getHouseholdPlace());
                }
                item.setAreaCode(household.getAreaCode());
                item.setBdTime(new Date());
                item.setBdStatus(HouseholdBdEnum.ok.getType());
                item.setBdMsg(HouseholdBdEnum.ok.getName());
            } else {
                item = studentINfoBd(item);
            }
            //3，查询结果，设置到学生户籍比对表中
            updatedItems.add(item);
        }
        // 批量更新学生户籍比对表
        eduHouseholdBdIntegration.batchEdit(updatedItems);

    }

    /**
     * 调用大数据接口进行查询
     * @param item
     * @return
     */
    private EduHouseholdBdVO studentINfoBd(EduHouseholdBdVO item) {
        try {
            HouseHoldSaveVO vo = new HouseHoldSaveVO();
            vo.setIdcard(item.getIdcard());
            PageInfo<EduHouseholdVO> eduHouseholdVOPageInfo = this.queryBigDataHousehold(vo);
            List<EduHouseholdVO> list = eduHouseholdVOPageInfo.getList();
            if (ObjectUtils.isEmpty(list)) {
                for (EduHouseholdVO eduHouseholdVO : list) {
                    if (eduHouseholdVO.getIdcard().equals(item.getIdcard())) {
                        item.setAreaCode(eduHouseholdVO.getAreaCode());
                        break;
                    }
                }
            } else {
                item.setAreaCode(null);
            }
            item.setBdTime(new Date());
            item.setBdStatus(HouseholdBdEnum.ok.getType());
            item.setBdMsg(HouseholdBdEnum.ok.getName());
        } catch (Exception e) {
            item.setBdTime(new Date());
            item.setAreaCode(null);
            item.setBdStatus(HouseholdBdEnum.error.getType());
            item.setBdMsg(e.getMessage());
            return item;
        }
        return item;
    }

    private Boolean checkEnroll(String idcard, Integer year) {
        if (year == null) {
            year = eduHelper.thisYear();
        }
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard, idcard)
                .eq(EduStudentEnroll::getYear, year)
                .in(EduStudentEnroll::getEnrollStatus, enrollStatusList);
        if (eduStudentEnrollService.count(enrollQueryWrapper) <= 0) {
            return false;
        }
        return true;
    }
}
